package com.sports.demo.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sports.demo.basic.BasicController;
import com.sports.demo.model.Facilities;
import com.sports.demo.model.User;
import com.sports.demo.req.NameReq;
import com.sports.demo.req.UserReq;
import com.sports.demo.service.UserService;
import com.sports.demo.utils.AssertUtils;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 用户 前端控制器
 * </p>
 *
 * @author SRG
 * @since 2022-03-13
 */
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController extends BasicController<UserService, User> {

  @PostMapping({"getPage"})
  public IPage<User> page(@RequestBody NameReq req) {
    LambdaQueryWrapper<User> query = Wrappers.lambdaQuery(User.class).orderByDesc(User::getId);
    if (StringUtils.hasText(req.getName())) {
      query.like(User::getName, req.getName());
    }
    return getBasicService().page(req.getPlusPage(), query);
  }

  @ApiOperation(value="登录", notes="")
  @PostMapping("login")
  public User login(@RequestBody @Validated User user) {
    AssertUtils.notBlank(user.getName(),"登录名不能为空");
    AssertUtils.notBlank(user.getPassword(),"密码不能为空");
    User user2 =getBasicService().getOne(Wrappers.lambdaQuery(User.class).
            eq(User::getName , user.getName()));
    AssertUtils.notNull(user2,"用户不存在");
    User user1 =getBasicService().getOne(Wrappers.lambdaQuery(User.class).
        eq(User::getName , user.getName()).eq(User::getPassword,user.getPassword()));
    AssertUtils.notNull(user1,"密码错误");
    return user1;
  }
  @ApiOperation(value="注册", notes="")
  @PostMapping("register")
  public boolean register(@RequestBody @Validated UserReq req) {
    AssertUtils.notBlank(req.getName(),"登录名不能为空");
    AssertUtils.notBlank(req.getPassword(),"密码不能为空");
    AssertUtils.notBlank(req.getNewpassword(),"确认密码不能为空");
    AssertUtils.isFalse(req.getPassword()==req.getNewpassword(),"两次输入的密码不一致");
    AssertUtils.isNull(getBasicService().getOne(Wrappers.lambdaQuery(User.class).
        eq(User::getName , req.getName())),"该登录名已被注册");
    User user1 = new User();
    user1.setName(req.getName());
    user1.setPassword(req.getPassword());
    return getBasicService().saveForUniqueKey(user1);
  }


}
